package com.device.config;

import com.device.entity.User;
import com.device.entity.UserCredentials;
import com.device.repository.UserRepository;
import com.device.repository.UserCredentialsRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.UUID;

@Component
public class DataInitializer implements CommandLineRunner {
    
    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private UserCredentialsRepository userCredentialsRepository;
    
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;
    
    @Override
    public void run(String... args) throws Exception {
        try {
            // 检查是否已存在管理员用户
            if (!userRepository.existsByEmail("sysadmin@thingsboard.org")) {
                // 创建管理员用户
                User adminUser = new User();
                adminUser.setId(UUID.randomUUID());
                adminUser.setEmail("sysadmin@thingsboard.org");
                adminUser.setFirstName("Admin");
                adminUser.setLastName("User");
                adminUser.setAuthority("SYS_ADMIN");
                adminUser.setCreatedTime(System.currentTimeMillis());
                adminUser.setVersion(1L);
                
                userRepository.save(adminUser);
                
                // 创建用户凭据
                UserCredentials credentials = new UserCredentials();
                credentials.setId(UUID.randomUUID());
                credentials.setUserId(adminUser.getId());
                credentials.setPassword(passwordEncoder.encode("Expert68720205"));
                credentials.setEnabled(true);
                credentials.setCreatedTime(System.currentTimeMillis());
                credentials.setFailedLoginAttempts(0);
                credentials.setAdditionalInfo("{}");
                
                userCredentialsRepository.save(credentials);
            }
        } catch (Exception e) {
            System.err.println("初始化管理员用户时出错: " + e.getMessage());
            // 不抛出异常，让应用继续启动
        }
    }
} 